package models

import (
	"encoding/json"
	"errors"
	"time"
)

type Blog struct {
	BlogID     uint64    `json:"blog_id" db:"blog_id"`
	Title      string    `json:"title" db:"title"`
	Author     string    `json:"author" db:"author"`
	Tags       string    `json:"tags" db:"tags"`
	Short      string    `json:"short" db:"short"`
	Content    string    `json:"content" db:"content"`
	CreateTime time.Time `json:"-" db:"create_time"`
}

func (p *Blog) UnmarshalJSON(data []byte) (err error) {
	required := struct {
		Title   string `json:"title" db:"title"`
		Tags    string `json:"tags" db:"tags"`
		Short   string `json:"short" db:"short"`
		Content string `json:"content" db:"content"`
	}{}
	err = json.Unmarshal(data, &required)
	if err != nil {
		return
	} else if len(required.Title) == 0 {
		err = errors.New("博客标题不能为空")
	} else if len(required.Tags) == 0 {
		err = errors.New("博客标签不能为空")
	} else if len(required.Short) == 0 {
		err = errors.New("博客简介不能为空")
	} else if len(required.Content) == 0 {
		err = errors.New("博客内容不能为空")
	} else {
		p.Title = required.Title
		p.Tags = required.Tags
		p.Short = required.Short
		p.Content = required.Content
	}
	return
}
